package com.uni.controllers;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

import com.uni.controllers.editors.ListEditor;
import com.uni.controllers.validation.GroupValidator;
import com.uni.db.GenericService;
import com.uni.db.UserService;
import com.uni.domain.Group;
import com.uni.domain.User;

@Controller
@RequestMapping("/groupEdit.htm")
@SessionAttributes(types = Group.class)
public class GroupEditForm {

	@Autowired
    @Qualifier("groupService")
    private GenericService<Group> groupService;
	
	@Autowired
    @Qualifier("userService")
    private UserService userService;
    
    @InitBinder
    public void initBinder(WebDataBinder binder){
        binder.registerCustomEditor(Set.class, new ListEditor(userService));
    }

    @RequestMapping(method = RequestMethod.GET)
    public String setupForm(@RequestParam(value="id", required=false) Long id, ModelMap model) {
    	Group group;
    	if(id != null){
	    	group = groupService.get(id);
	    	if(group == null){
	    		group = new Group();
	    	}
    	} else {
    		group = new Group();
    	}
    	List<User> outUsers = userService.listAll();
        for(int i = 0 ; i < outUsers.size() ; i ++){
        	if(outUsers.get(i).getGroup() != null){
        		outUsers.remove(i);
        		i--;
        	}
        }
        model.addAttribute("group", group);
        model.addAttribute("outUsers", outUsers);
        return "groupEdit";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String processSubmit(@ModelAttribute Group group,
    		BindingResult result, SessionStatus status ,
    		HttpServletRequest request, 
    		@RequestParam(value="students", required=true) String[] users) throws IOException, ServletException {
    	new GroupValidator().validate(group, result);
        if (result.hasErrors()) {
            return "groupEdit";
        } 
        List<Long> ids = new ArrayList();
        
        for(String sid : users){
        	try{
        		ids.add(Long.getLong(sid));
        	} catch (NumberFormatException e){
        		return "groupEdit";
        	}
        }
        group.setStudents(new HashSet<User>(userService.getUsers(ids)));
        groupService.save(group);
        return "redirect:/group/list";
    }
}
